package com.mystack;


import java.util.Stack;

/**
 * @BelongsProject: DataStructures
 * @BelongsPackage: com.mystack
 * @Author: 江岸
 * @CreateTime: 2021-01-10 16:32
 * @Description: 用栈模拟计算器
 */
public class Caculater {
    public static void main(String[] args) {
        CaStack<Integer> numStack = new CaStack();
        CaStack<Character> caStack = new CaStack();
        String str = "40/2+3+6*2-5*4+90";
        char[] chars = str.toCharArray();
        for (int i = 0;i<chars.length;i++){
            //是否符号
            if (isFuhao(chars[i])){
                if (caStack.isEmpty()){
                    caStack.push(chars[i]);
                }else {
                    //不为空需要做逻辑处理
                    //输入的操作符的等级小于等于栈中操作符，则先计算栈
                    while (!caStack.isEmpty() && contast(chars[i],caStack.peek())<=0){
                        int calc = calc(numStack.pop(), numStack.pop(), caStack.pop());
                        numStack.push(calc);
                    }
                    caStack.push(chars[i]);
                }
            }else {
                try {
                    String num = "";
                    while (true){
                        if (i<chars.length && isNum(chars[i])){
                            num = num + chars[i];
                            i++;
                        }else {
                            i--;
                            break;
                        }
                    }
                    numStack.push(Integer.parseInt(num));
                }catch (Exception e){
                    System.err.println("输入错误符号:"+chars[i+1]);
                    i++;
                }
            }
        }
        while (true){
            if (caStack.isEmpty()){
                break;
            }
            int  num = 0;
            num = calc(numStack.pop(),numStack.pop(),caStack.pop());
            numStack.push(num);
        }
        System.out.println(numStack.pop());
    }

    static boolean isFuhao(char a){
        if (a=='+' || a=='-' || a=='*' || a=='/'){
            return true;
        }
        return false;
    }

    static boolean isNum(char a){
        try {
            Integer.parseInt(a + "");
            return true;
        }catch (Exception e){
            return false;
        }
    }

    static int contast(char out,char in){
        int i = getLevel(out) - getLevel(in);
        return i;
    }

    static int getLevel(char a){
        if (a=='+'||a=='-'){
            return 0;
        }else {
            return 1;
        }
    }

    static int  calc(int a,int b,char c){
        if (c=='+'){
            return a+b;
        }else if (c=='*'){
            return a*b;
        }else if(c=='-'){
            return b-a;
        }else {
            return b/a;
        }
    }
}

class CaStack<T>  extends Stack<T>{

}


